package com.elight.sys.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.elight.controller.BaseController;
import com.elight.entity.LayPadding;
import com.elight.entity.SysUserExt;
import com.elight.filter.AuthorizeChecked;
import com.elight.sys.entity.SysUser;
import com.elight.sys.entity.SysUserLogOn;
import com.elight.sys.entity.SysUserRoleRelation;
import com.elight.sys.service.SysUserService;
import com.elight.utils.GsonUtils;
import com.elight.utils.OperatorProvider;
import com.elight.utils.StringUtils;

@RestController
@RequestMapping(value = "/System/User")
public class UserController extends BaseController {
	@Autowired
	private SysUserService userService;
	
	/**
	 * 用户列表页
	 * @return
	 */
	@AuthorizeChecked()
	@RequestMapping(value = "/Index", method = { RequestMethod.GET })
	public ModelAndView index() {
		return new ModelAndView("/System/User/Index");
	}
	
	
	/**
	 * 获得用户列表分页
	 * @param pageIndex
	 * @param pageSize
	 * @param keyWord
	 * @return
	 */
    @AuthorizeChecked()
	@RequestMapping(value = "/Index", method = { RequestMethod.POST },produces = "application/json; charset=utf-8")
    public String index(int pageIndex, int pageSize, String keyWord)
    {
        int totalCount = userService.getTotalCount(keyWord);
        List<SysUser> pageData = userService.getList((pageIndex-1)*pageSize, pageSize, keyWord);
        LayPadding<SysUser> result = new LayPadding<SysUser>();
        result.setResult(true);
        result.setMsg("success");
        result.setList(pageData);
        result.setCount(totalCount);
        return GsonUtils.objToJSON(result);
    }

    @AuthorizeChecked()
    @RequestMapping(value = "/Form", method = { RequestMethod.GET })
    public ModelAndView form()
    {
        return new ModelAndView("/System/User/Form");
    }
    /**
    * 修改新增用户登录账号
    * @param session
    * @param model
    * @param password
    * @param roleIds
    * @return
    */
    @AuthorizeChecked()
	@RequestMapping(value = "/Form", method = { RequestMethod.POST },produces = "application/json; charset=utf-8")
    public String form(HttpSession session,SysUser model, String password, String roleIds)
    {
    	try {
    		if (StringUtils.isNullOrEmpty(model.getId()))
    		{
    			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    			Date defaultDt = format.parse(model.getStrBirthDay());
    			model.setBirthday(defaultDt);
    			//新增用户基本信息。
    			model.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
    			int n = userService.insert(model);
    			if(n<=0)
    				return error();
    			//新增用户角色信息。
    			userService.setRole(session,model.getId(), roleIds.split(","));
    			//新增用户登陆信息。
    			SysUserLogOn userLogOnEntity = new SysUserLogOn();
    			userLogOnEntity.setUserId(model.getId());
    			userLogOnEntity.setPassword(password);
    			int userLoginId = userService.insertUserLogOn(userLogOnEntity);
    			return userLoginId>0 ? success() : error();
    		}
    		else
    		{
    			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    			Date defaultDt = format.parse(model.getStrBirthDay());
    			model.setBirthday(defaultDt);
    			//更新用户基本信息。
    			model.setModifyUser(OperatorProvider.getCurrent(session).getAccount());
    			int row = userService.update(model);
    			//更新用户角色信息。
    			userService.setRole(session,model.getId(),roleIds.split(","));
    			return row > 0 ? success() : error();
    		}
    	}catch(Exception ex) {
        	return error();
        }
    }

    /**
     * 用户信息详情页
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/Detail", method = { RequestMethod.GET })
    public ModelAndView detail()
    {
        return new ModelAndView("/System/User/Detail");
    }

    /**
     * 根据主键得到用户信息
     * @param primaryKey
     * @return
     */
    @RequestMapping(value = "/GetForm", method = { RequestMethod.POST },produces = "application/json; charset=utf-8")
    public String getForm(String primaryKey)
    {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SysUser entity = userService.get(primaryKey);
        entity.setStrBirthDay(format.format(entity.getBirthday()));
        List<SysUserRoleRelation> roleRelationList=  userService.getUserRoleList(entity.getId());
        List<String> roleId = new ArrayList<String>();
        for(SysUserRoleRelation item : roleRelationList) {
        	roleId.add(item.getRoleId());
        }
        SysUserExt entityExt = new SysUserExt();
        entityExt.setAccount(entity.getAccount());
        entityExt.setAddress(entity.getAddress());
        entityExt.setAvatar(entity.getAvatar());
        entityExt.setBirthday(entity.getBirthday());
        entityExt.setCompanyId(entity.getCompanyId());
        entityExt.setCreateTime(entity.getCreateTime());
        entityExt.setCreateUser(entity.getCreateUser());
        entityExt.setDeleteMark(entity.getDeleteMark());
        entityExt.setDepartmentId(entity.getDepartmentId());
        entityExt.setDeptName(entity.getDeptName());
        entityExt.setEmail(entity.getEmail());
        entityExt.setGender(entity.getGender());
        entityExt.setId(entity.getId());
        entityExt.setIsEnabled(entity.getIsEnabled());
        entityExt.setMobilePhone(entity.getMobilePhone());
        entityExt.setModifyTime(entity.getModifyTime());
        entityExt.setModifyUser(entity.getModifyUser());
        entityExt.setNickName(entity.getNickName());
        entityExt.setRealName(entity.getRealName());
        entityExt.setSignature(entity.getSignature());
        entityExt.setSortCode(entity.getSortCode());
        entityExt.setStrBirthDay(entity.getStrBirthDay());
        entityExt.setRoleId(roleId);
        return GsonUtils.objToJSON(entityExt);
    }

    /**
     * 删除用户信息
     */
    @AuthorizeChecked()
   	@RequestMapping(value = "/Delete", method = { RequestMethod.POST },produces = "application/json; charset=utf-8")
    public String delete(String userIds)
    {
        //多用户删除。
        int row = userService.delete(userIds.split(","));
        userService.deleteUserRoleRelation(userIds.split(","));
        userService.deleteLogOnUser(userIds.split(","));
        return row > 0 ? success() : error();
    }
    /**
     * 根据账号得到用户信息
     * @param userName
     * @return
     */
    @RequestMapping(value = "/CheckAccount", method = { RequestMethod.POST },produces = "application/json; charset=utf-8")
    public String checkAccount(String userName)
    {
        SysUser userEntity = userService.getByUserName(userName);
        if (userEntity != null)
        {
            return error("已存在当前用户名，请重新输入");
        }
        return success("恭喜您，该用户名可以注册");
    }
}
